package doc.talk;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;


public class Networker {
	
	//constant representing the URL of the server
	public final String REMOTE_SERVER_LOCATION = "http://fishbot.co.cc";
	
	//necessary variables for function sharing
	private URL target;
	private URLConnection link;
	BufferedReader instream;
	BufferedWriter outstream;
	
	
    public boolean establishConnection() //returns true if a connection is established, false if connection fails
    {
    	try{
    	target = new URL(REMOTE_SERVER_LOCATION);//generates a URL object from the server location
    	link = target.openConnection();//generates a connection from the URL
    	link.connect();//opens the connection
    	}
    	catch(IOException exc)
    	{
    		return false;
    	}
    	return true;

    }
    
    public boolean openInstream() //requires that establishConnection has already run and returned true. also, leaves the connection open
    {
    	try{
    	instream = new BufferedReader(new InputStreamReader(link.getInputStream())); //opens an input stream from the file
    	}
    	catch(IOException exc)
    	{
    		return false;
    	}
    	return true;
    }
    
    public String httpGet()//expects that instream is already functional
    {
    	String lineread = "";
    	try{
    	lineread = instream.readLine();//try to get a new line
    	}
    	catch(IOException exc)
    	{
    	 lineread = "ERROR";//if a problem occurs, set to ERROR
    	}
    	
    	return lineread;//returns a line, EOF, or ERROR

    }
    
  
    public boolean closeInstream()//tries to close the input stream
    {
    	try{
    		instream.close();
    	}
    	catch(IOException exc)
    	{
    		return false;
    	}
    	return true;
    }
    	
    
    public boolean openOutstream()
    {
    	try{
        	outstream = new BufferedWriter(new OutputStreamWriter(link.getOutputStream())); //opens an input stream from the file
        	}
        	catch(IOException exc)
        	{
        		return false;
        	}
        	return true;
    }

    public boolean httpPost(String writeable)
    {
    	try{
    		outstream.write(writeable);
    	}
    	catch(IOException exc)
    	{
    		return false;
    	}
    	return true;
    }

    public boolean closeOutstream()
    {
    	try{
    		outstream.close();
    	}
    	catch (IOException exc)
    	{
    		return false;
    	}
    	return true;
    }

}